package number_operatation.leetcode.easy;

/**
 * @author bruin_du
 * @description 二进制加法
 * @date 2022/7/31 23:53
 **/
public class OfferII002_AddBinary {
    public String addBinary(String a, String b) {
        method1(a, b);

        //模拟进位的过程
        return method2(a, b);
    }

    private String method1(String a, String b) {
        StringBuilder sbA = new StringBuilder(a).reverse();
        StringBuilder sbB = new StringBuilder(b).reverse();
        char[] arrL = sbA.toString().toCharArray();
        char[] arrS = sbB.toString().toCharArray();
        if (arrL.length < arrS.length) {
            char[] tmp = arrL;
            arrL = arrS;
            arrS = tmp;
        }
        char carry = '0';
        int[] arr = new int[]{3 * '0', 2 * '0' + '1', '0' + 2 * '1', 3 * '1'};
        StringBuilder sb = new StringBuilder();
        int i = 0;
        for (; i < arrL.length; i++) {
            char x = '0';
            if (i < arrS.length) {
                x = arrS[i];
            }
            int sum = x + arrL[i] + carry;
            if (sum == arr[0]) {
                carry = '0';
                sb.append(0);
            } else if (sum == arr[1]) {
                carry = '0';
                sb.append(1);
            } else if (sum == arr[2]){
                carry = '1';
                sb.append(0);
            } else {
                carry = '1';
                sb.append(1);
            }
        }
        if (carry == '1') {
            sb.append(1);
        }
        return sb.reverse().toString();
    }

    private String method2(String a, String b) {
        int n = Math.max(a.length(), b.length()), carry = 0;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++) {
            carry += i < a.length() ? (a.charAt(a.length() - i - 1) - '0') : 0;
            carry += i < b.length() ? (b.charAt(b.length() - i - 1) - '0') : 0;
            sb.append(carry % 2);
            carry = carry / 2;
        }
        if (carry == 1) {
            sb.append(1);
        }
        return sb.reverse().toString();
    }
}
